package com.gin.kotlin.gf2gamecommunity.viewmodel

import androidx.lifecycle.ViewModel
import com.gin.kotlin.form.HeroListForm
import com.gin.kotlin.form.HeroineIdForm
import com.gin.kotlin.form.PrivacyForm
import com.gin.kotlin.form.UserIdForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.livedata.ParamCachedLiveData
import com.gin.kotlin.gf2gamecommunity.callback.AbstractNothingCallback
import com.gin.kotlin.response.ListData
import com.gin.kotlin.response.Res
import com.gin.kotlin.response.game.GameInfo
import com.gin.kotlin.response.game.Heroine
import com.gin.kotlin.response.user.SetPrivacyBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class GameInfoViewModel : ViewModel() {
    val gameInfo = ParamCachedLiveData<Res<GameInfo>, GameInfo, Int?>(
        requestMethod = { api().get(UserIdForm(it)) },
        bodyTransform = { it.data },
    )

    fun setDisplay(uid: Int?, form: PrivacyForm) = api().setDisplay(form).enqueue(object : Callback<Res<SetPrivacyBody>?> {
        override fun onResponse(call: Call<Res<SetPrivacyBody>?>, response: Response<Res<SetPrivacyBody>?>) {
            gameInfo.fetch(uid, true)
        }

        override fun onFailure(call: Call<Res<SetPrivacyBody>?>, throwable: Throwable) {
            App.onFailed(throwable)
        }
    })

    val heroList = ParamCachedLiveData<Res<ListData<Heroine>>, List<Heroine>, HeroListForm>(
        requestMethod = { api().heroList(it) },
        bodyTransform = { it.data?.list },
    )

    fun setHeroSeq(param: HeroListForm, form: HeroineIdForm) = api().setHeroSeq(form).enqueue(object : AbstractNothingCallback() {
        override fun onSuccess(message: String) {
            App.toast(message)
            heroList.fetch(param, true)
            gameInfo.fetch(null, true)
        }
    })

    private fun api() = App.INSTANCE.api.gameInfoApi


    companion object {
        private val TAG = GameInfoViewModel::class.java.simpleName
    }
}